layui.use(['laytpl','upload'], function(){
	var laytpl = layui.laytpl;
	var $ = layui.$;
	 var upload = layui.upload;
	//接收上一个页面的传值
	function getQueryVariable(variable){
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    for (var i=0;i<vars.length;i++) {
	        var pair = vars[i].split("=");
	        if(pair[0] == variable){return pair[1];}
	    }
	    return(false);
	}
	function initData(id,data,getTpl){
		view = document.getElementById(id);
		laytpl(getTpl).render(data, function(html){
		  view.innerHTML = html;
		});
	}
	//执行实例
	  var uploadInst = upload.render({
	    elem: '#changeAvatar' //绑定元素
	    ,url: '../file/upload2' //上传接口
	    ,done: function(res){
	      var url = res.url;
	      var id = layui.sessionData('user').data.id;
			var data ={
					'id': id,
					'avatar': url
			}
			console.log(data)
			$.ajax({
		        type: "PUT",
		        contentType:"application/json;charset=utf-8",
		        url: "http://127.0.0.1:8080/blog/user/user",
		        data:JSON.stringify(data),
		        success: function (res) {
		        	var rs = JSON.parse(res);
		        	if(rs.code == 200){
		        		layer.msg("修改成功！")
		        		var user = layui.sessionData('user').data;
		        		user.avatar = url;
		        		layui.sessionData('user',{
		        			key:'data',
		        			value:user
		        		})
		        		window.location.reload();
		        	}
		        	
		        }
	   		 });
	    }
	    ,error: function(){
	      //请求异常回调
	    }
	  });
	$('#updateInfo').on('click',function(){
		var user = layui.sessionData('user').data;
		layer.open({
            type: 1 //Page层类型
            ,fixed: false
            ,skin: 'layui-layer-molv'
            ,area: ['500px', '300px']
            ,title: ['修改用户信息','font-size:18px']
            ,btn: ['确定', '取消'] 
            ,shadeClose: true
            ,shade: 0 //遮罩透明度
            ,maxmin: true //允许全屏最小化
            ,content:$("#window")  //弹窗路径
            ,success:function(layero,index){
            var user = layui.sessionData('user');
           	$('#name').val(user.data.name);
           	$('#email').val(user.data.email); 
           	$('#password').val('');  
            },yes:function(index,layero){
            	var data = {
            			'id': layui.sessionData('user').data.id
            			,'name': $('#name').val()
            			,'email': $('#email').val()
                      	 ,'password': $('#password').val()
            	}
           	 $.ajax({
                    url: "/blog/"+'user/user',    //换成自己的url
                    type: "PUT",
                    dataType: "json",
                    contentType : 'application/json;charset=utf-8',//重要
                    data: JSON.stringify(data),
                    success: function (e) {
                        if (e.code == 0) {
                            layer.msg(e.msg);
                        } else {
                            layer.msg(e.msg);
                        }
                        user.name = $('#name').val();
                        user.email = $('#email').val()
                        user.password = $('#password').val()
                        layui.sessionData("user",{
                        	key: "data",
                        	value: user
                        })
                        
                    },
                    error: function (e) {
                        layer.msg(e);
                    }
                })    
            },end:function(index,layero){
            	window.location.reload();
            }
        });
	})
	var dat = {'data':{ //数据
		  "id": 0,
		  "avatar":"./static/images/unLogin.png"
		  ,"name":	"未登录"
}}
	 function intiKMInfo() {
			var user = layui.sessionData('user');
			if(user == null || user == undefined ||$.isEmptyObject(user)){
				window.location.href="./index.html"
				user = dat;
				$('#edit').addClass('layui-hide')
			}
			$('#avatar').attr('src',user.data.avatar);
			console.log(user.data);
			$('#peointr').val(user.data.name);
			var getTpl = person.innerHTML
			initData('account',user,getTpl);
			//加载分类
            $.ajax({
                type: "GET",
                url: "http://127.0.0.1:8080/blog/category/categoryTypeList",
                success: function (data) {   
                	var res = { //数据
					  "data":{'categoryList':[
						  {
							  'id':1,
							  content:'PHP'
							  },
						  {
							  'id':2,
							  content:'Java'},
						  {
							  'id':3,
							   content:'Python'},
						  {
						      'id':4,
							   content:'C++'}]}
					}
                	var rs = JSON.parse(data);
                	console.log(rs)
                	var getTpl = category.innerHTML
                	if(rs.data!=null){
                		initData('categoryList',rs.data,getTpl);
                	}else{
                		initData('categoryList',res.data,getTpl);
                	}
                	layui.data('category', {
                		  key: 'categoryList'
                		  ,value: rs.data
                		});
                	var id = getQueryVariable("id");
                	rs.data.data.list.forEach(item=>{
                		if(item.id == id){
							console.log(item)
							document.getElementById("cite").innerHTML=item.content;
						}
                	})

                }
            });
          //加载文章
            $.ajax({
                type: "GET",
                url: "http://127.0.0.1:8080/blog/article/getArticleByUserId?page="+1+"&limit="+10,
                data: {
                	"userId": layui.sessionData("user").data.id
                },
                success: function (data) {
                	var rs = JSON.parse(data);
                	console.log(rs)
                	var getTpl = articleList.innerHTML
                	var getTp = hotArticle.innerHTML
                	if(rs.data!=null){
                		initData('articleListView',rs.data,getTpl);
                		initData('hotArticleView',rs.data,getTp);
                	}else{
                		initData('articleListView',[],getTpl);
                		initData('hotArticleView',[],getTp);
                	} 
                	layui.laypage.render({
                	    elem: 'pages' //注意，这里的 test1 是 ID，不用加 # 号
                	    ,count: rs.data.data.total //数据总数，从服务端得到
                	    ,limit:10
                	    ,jump: function(obj, first){
                	        //obj包含了当前分页的所有参数，比如：
                	        console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                	        console.log(obj.limit); //得到每页显示的条数
                	        
                	        //首次不执行
                	        if(!first){
                	        	$.ajax({
                	                type: "GET",
                	                url: "http://127.0.0.1:8080/blog/article/articleList?page="+obj.curr+"&limit="+obj.limit,
                	                success: function (data) {
                	                	var rs = JSON.parse(data);
                	                	console.log(rs)
                	                	var articleListTpl = articleList.innerHTML
                	                	initData('articleListView',rs.data,articleListTpl);
                	                }
                	        	})
                	        }
                	      }
                  	});
                }
            });
        }
	intiKMInfo();
    $('#logout').on('click',function(){
    	layui.sessionData('user',{
    		key:'data',
    		remove: true
    	})
    	layer.msg("注销成功！")
    	window.location.href="./index.html"
    })
    $('#delete').on('click',function(res){
    	console.log(res)
    })
	})
	layui.carousel.render({
	    elem: '#carousel'
	    ,width: '100%' //设置容器宽度
	    ,arrow: 'always' //始终显示箭头
	    //,anim: 'updown' //切换动画方式
  	});
  	function deleted(id){
  		console.log(id)
        //删除文章
        $.ajax({
            type: "DELETE",
            url: "http://127.0.0.1:8080/blog/article/article/"+id,
            dataType: "json",
            contentType : 'application/json;charset=utf-8',//重要
            success: function (data) {
            	if(data.code==200){
            		window.location.reload();
            	}
            	console.log(rs)
            	window.location.reload();
            }
        });
  		
  	}